package com.job.project.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;

/**
 * @author 王博
 */
@Slf4j
@Component
@ServerEndpoint("/WebSocket")
public class WebSocketServer {

//    private Session session;

    @OnOpen
    public void onOpen(Session session) {
//        this.session = session;
//        WebSocketManager.sentToUser(session, "WebSocket is connected!");
//        WebSocketManager.addWebSocketServer(this);
        log.info("与SessionId：{}建立连接", session.getId());
        session.getAsyncRemote().sendText("哈哈哈哈哈，你好啊，你链接了我，我是websocket链接，请给我发消息吧");
    }

    @OnClose
    public void onClose() {
//        WebSocketManager.removeWebSocketServer(this);
        log.info("WebSocket连接关闭");
    }

    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自SessionId:{}的消息:{}", session.getId(), message);
        session.getAsyncRemote().sendText("我接到的消息是："+message+";我给你的消息也是："+message);
    }

    @OnError
    public void onError(Session session, Throwable error) {
        log.error("Session:{}的WebSocket发生错误", session.getId(), error);
    }

  /*  public Session getSession() {
        return session;
    }

    public String getSessionId() {
        return session.getId();
    }*/
}
